<html>
    <head>
        <title>Edit Information</title>

        <link href="style3.css" rel="stylesheet" type="text/css" />

        <SCRIPT language="javascript">
            //counter
            var x = 0;
            //function to add text field
            function add(type) {

                //Create an input type dynamically.
                var element = document.createElement("input");

                //Assign different attributes to the element.
                type =  type + x;
                element.setAttribute("type", 'email');
                element.setAttribute("name", type);
                //Create a fooBar type dynamically.
                var foo = document.getElementById("fooBar");

                //Append the element in page (in span).
                foo.appendChild(element);
                //increment the value of x by 1        
                x = x + 1;
            }
            //a function that allows only numbers and letters to be entered
            function alpha(e) {
                var k;
                document.all ? k = e.keyCode : k = e.which;
                return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
            }
                    
            //a function that allows only numbers to be entered                
            function isNumberOnly(evt)
            {
                var charCode = (evt.which) ? evt.which : event.keyCode
                if (charCode > 31 && (charCode < 48 || charCode > 57)){
                    alert("Please enter numbers only.");
                    return false;
                }
                return true;
            }
            //a function that allows only letters to be entered
            function isLetterOnly(evt) {
                evt = (evt) ? evt : event;
                var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
                    ((evt.which) ? evt.which : 0));
                if (charCode > 31 && (charCode < 65 || charCode > 90) &&
                    (charCode < 97 || charCode > 122)) {
                    alert("Please enter letters only.");
                    return false;
                }
                return true;
            }
                                                    
                                                                   
        </SCRIPT>
    </head>
    <form name= "form" action = "" value = "Submit" method = "Post">
        <?php
        //Author Nour Ossama
        //check if the member id was passed from the previous page
       if (isset($_GET['member_id'])) {
            //save member_id in a variable $memberID
            $memberID = intval($_GET['member_id']);
            //calling function to execute it if condition was satisfied
            EditInfo($memberID);
        } else {//if no member id was passed
            echo "Sorry, action cannot be performed!";
        }
        


        /*
         * function EditInfo takes member_id and returns table with all  
         * info about member in textboxes to be edited
         */


        Function EditInfo($member_id) {
            //turn off the warnings that alert that there is an undefined index because there are no textboxes yet
            error_reporting(E_ALL ^ E_NOTICE);
            $conn = mysql_connect("localhost", "root", ""); //connect to the database

            if (!$conn) {//if no connection was made
                die('Could not connect:' . mysql_error());
            }
            //selection of the database
            mysql_select_db("mydb", $conn);

            //if save button was not yet clicked
            if (!isset($_POST['save'])) {

                //print title of the page
                echo "<h1>Edit Information</h1>";

                /*
                 * query that populates all the info of the member from the db
                 */
                $get_member_info = mysql_query("SELECT * 
                                    FROM member 
                                    WHERE member_id = '$member_id'") or die(mysql_error());
                while ($row = mysql_fetch_assoc($get_member_info)) {

                    //open table
                    echo "<table id=12>";

                    /*
                     * print First Name in a row 
                     * and in the column next to it print first_name from db inside the textbox  
                     */
                    echo "<tr>
         <td><b>First name:</b></td>
         <td><input type =\"text\" name =\"first_name\" value=\"$row[first_name]\" onkeypress=\"return isLetterOnly(event)\"/></td>
         </tr>";
                    /*
                     * print Last Name in a row 
                     * and in the column next to it print last_name from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Last name:</b></td>
        <td><input type =\"text\" name =\"last_name\" value=\"$row[last_name]\"onkeypress=\"return isLetterOnly(event)\"/></td>
        </tr>";
                    /*
                     * print Email in a row 
                     * and in the column next to it print email from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>E-mail:</b></td>
        <td><input type =\"email\" name =\"email\" value=\"$row[email]\"/></td>
        </tr>";

                    /*
                     * print Phone Number in a row 
                     * and in the column next to it print phoneNum from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Phone Number:</b></td>
        <td><input type =\"text\" name =\"phoneNum\" value=\"$row[phoneNum]\"onkeypress=\"return isNumberOnly(event)\"/></td>
        </tr>";

                    /*
                     * print Fax Number in a row 
                     * and in the column next to it print fax from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Fax Number:</b></td>
        <td><input type =\"text\" name =\"fax\" value=\"$row[fax]\"onkeypress=\"return isNumberOnly(event)\"/></td>
        </tr>";
                    /*
                     * print Address in a row 
                     * and in the column next to it print address from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Address:</b></td>
        <td><input type =\"text\" name =\"address\" value=\"$row[address]\"onkeypress=\"return alpha(event)\"/></td>
        </tr>";
                    /*
                     * print Affiliation in a row 
                     * and in the column next to it print affiliation from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Affiliation:</b></td>
        <td><input type =\"text\" name =\"affiliation\" value=\"$row[affiliation]\"onkeypress=\"return isLetterOnly(event)\"/></td>
        </tr>";
                    /*
                     * print Facebook Page in a row 
                     * and in the column next to it print fb_page from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Facebook Page:</b></td>
        <td><input type =\"url\" name =\"fb_page\" value=\"$row[fb_page]\"/></td>
        </tr>";
                    /*
                     * print LinkedIn Page in a row 
                     * and in the column next to it print linked_page from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Linked Page:</b></td>
        <td><input type =\"url\" name =\"linked_page\" value=\"$row[linked_page]\"/></td>
        </tr>";
                    /*
                     * print Website in a row 
                     * and in the column next to it print website from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Website:</b></td>
        <td><input type =\"url\" name =\"website\" value=\"$row[website]\"/></td>
        </tr>";
                    /*
                     * print Research Gate Site in a row 
                     * and in the column next to it print website from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Research Gate Site:</b></td>
        <td><input type =\"url\" name =\"research_gate_site\" value=\"$row[research_gate_site]\"/></td> 
        </tr>";
                    /*
                     * print Academic Gate Site in a row 
                     * and in the column next to it print academic_site from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Academic Site:</b></td>
        <td><input type =\"url\" name =\"academic_site\" value=\"$row[academic_site]\"/></td>
        </tr>";
                    /*
                     * print Mendeley Site in a row 
                     * and in the column next to it print mendeley_site from db inside the textbox  
                     */

                    echo "<tr>
        <td><b>Mendeley Site:</b></td>
        <td><input type =\"url\" name =\"mendeley_site\" value=\"$row[mendeley_site]\"/></td>
        </tr>";
                }
                //close table
                echo "</table>";
                //new line
                echo "<br>";
                /* query that retrieves all the other emails of the 
                 * member from table email
                 */
                $get_member_other_email = mysql_query("SELECT email
                                                           FROM emails
                                                           WHERE member_id = '$member_id'") or die(mysql_error());
                /* if result set of query is not empty i.e contains some values
                 * print Other Emails in a row
                 */
                if ($get_member_other_email) {
                    //open new table
                    echo '<table width="20%" id=22>';
                    echo "<tr>
                            <td><b>Other Email(s) (Click checkboxes of emails you wish to delete)</b></td>
                            </tr>";
                    //create counter and set it to zero
                    $counter = 0;
                    while ($row = mysql_fetch_assoc($get_member_other_email)) {
                        //increment counter by 1
                        $counter++;
                        /* and in the column next to Other Emails print 
                         * checkbox with the value of the email and a 
                         * text box which contains email from db, the hidden field stores the counter
                         */
                        echo "<tr>
                            <td><b> &nbsp; </b></td>
                            <td><input type=\"checkbox\" name=\"check_mail$counter\" value=\"$row[email]\">
                            <td><input type =\"text\" name =\"other_email$counter\" value=\"$row[email]\"/></td>
                            </tr>";

                        echo "<input type=\"hidden\" name=\"check_mail\" value=\"$counter\"/>";
                    }
                }

                /*
                 * printing the Add Extra Email button and then the textboxes that appear 
                 * each time this button is clicked
                 */
                echo "<tr>
                    <td><SELECT name=\"element\" hidden=\"true\">
                    </br>
                    <OPTION value=\"email\"></OPTION>
                    </SELECT>
                    </br>
                    <INPUT type=\"button\" name=\"add_email\" value=\"Add Extra Email\" onclick=\"add(document.forms[0].element.value)\"/></br>
                    <span id=\"fooBar\">&nbsp;</span>
                    </br>
                    </td>
                    </tr>";


                //close table
                echo "</table>";
                //nextline
                echo "<br>";
                //print the save button
                echo "<input type =\"submit\" name = \"save\" value = \"Save\" />";
            } else {//if save button was clicked
                //save all the entries in the textboxes in variables
                $first_name = $_POST['first_name'];
                $last_name = $_POST['last_name'];
                $main_email = $_POST['email'];
                $phoneNum = $_POST['phoneNum'];
                $fax = $_POST['fax'];
                $address = $_POST['address'];
                $affiliation = $_POST['affiliation'];
                $fb_page = $_POST['fb_page'];
                $linked_page = $_POST['linked_page'];
                $website = $_POST['website'];
                $research_gate_site = $_POST['research_gate_site'];
                $academic_site = $_POST['academic_site'];
                $mendeley_site = $_POST['mendeley_site'];
                //a query that checks the user is in the table and get his info
                $check_user = mysql_query("SELECT * FROM member WHERE member_id ='$member_id'");
                if (mysql_num_rows($check_user) > 0) {
                    //query that updates table member with new info from textboxes
                    $update_member_info = mysql_query("UPDATE member
                                                   SET first_name = '$first_name', 
                                                       last_name = '$last_name', 
                                                       email = '$main_email',
                                                       phoneNum = '$phoneNum',
                                                       fax = '$fax', 
                                                       address = '$address', 
                                                       affiliation = '$affiliation',
                                                       fb_page = '$fb_page', 
                                                       linked_page = '$linked_page',
                                                       website = '$website', 
                                                       research_gate_site = '$research_gate_site',
                                                       academic_site = '$academic_site', 
                                                       mendeley_site = '$mendeley_site'
                                                    WHERE member_id = '$member_id'") or die(mysql_error());

//counter $X that loops on textboxes, their maximum should be 19
                    for ($x = 0; $x < 19; $x++) {
                         $email = 'email';
                        //Append Email Number
                        $email = $email . $x;
                        //checking if any values were entered in the textbox
                        if (isset($_POST[$email])) {
                            //assign the textbox value to the variable $added_email
                            $added_email = $_POST[$email];
                            
                            //a query that checks that the added_email was not enetered before
                            $if_email_exists = mysql_query("SELECT m.email, e.email FROM member m , emails e WHERE (e.email = '$added_email')OR(m.email = '$added_email')") or die(mysql_error());
                            $num_of_rows = 0;
                            while ($row = mysql_fetch_assoc($if_email_exists)) {
                                $num_of_rows++;
                            }
                            //if result of query is empty
                            if ($num_of_rows == 0) {

                                //insert the id and added_email in the database
                                $insert_other_email = mysql_query("INSERT INTO emails (member_id, email) VALUES ('$member_id', '$added_email')") or die(mysql_error());
                            } else {//alert to the user that the email is being used by someone else
                                ?>
                                
                                <script type="text/javascript">
                                    window.alert("<?php echo $added_email;
                        ?> is already in use")
                                </script>
                                <?php
                            }
                        }
                    }



                    //loop on the array of checkboxes
                    for ($counter = 1; $counter <= $_POST['check_mail']; $counter++) {
                        //if the checkbox was clicked
                        if (isset($_POST["check_mail$counter"])) {
                            //save the value of the textbox in $other_email
                            $other_mail = $_POST["check_mail$counter"];
                            //a query that deletes the $other_email from table emails
                            $delete_other_email = mysql_query("DELETE FROM emails 
                                                     WHERE member_id='$member_id' 
                                                     AND email='$other_mail'") or die(mysql_error());
                        }
                    }

                    //if either of the two queries executed successfully
                    if ($update_member_info || $insert_other_email || $delete_other_email) {
                        //echo heading "info saved"
                        echo "<h2>Information Saved!</h2>";
                        echo "<br>";
                        //load the profile page with new info and the Edit Information hyperlink
                        print "<a style=\"float:right\" href=\"EditInfo.php?member_id={$member_id}\">Edit Information</a>";

                        include("ProfilePage.php");
                    } else { //if queries were not successful
                        echo ("<p>There was an error in executing the query: " .
                        mysql_error() . "</p>");
                    }
                }
            }
        }
        ?>
    </form>
</html>
